package com.demoo.zjsu.service.smartwebsite.zjgsu;

import com.demoo.zjsu.dao.smartwebsite.SmartWebDAO;
import com.demoo.zjsu.model.smartwebsite.PageTwo;
import com.demoo.zjsu.service.smartwebsite.OnlyPhotoResolver;
import com.demoo.zjsu.service.smartwebsite.Page;
import com.demoo.zjsu.util.smartwebsite.WebsiteUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jshjsh on 2016/8/18.
 *  校园风光处理
 *  因为确定图片页面的数量会不断变化，所以在这里改写resolver方法
 *  会抛出异常,抛出异常正常结束
 */
@Service
public class SchoolViewService extends OnlyPhotoResolver{

    @Override
    public PageTwo getPageTwo(Element element) {
        Elements img = element.select("table").eq(0).select("img");
        String key = img.attr("src");
        String title = element.select("table").eq(1).text();
        if (title == null || title.equals("")) {
            return null;
        }
        return new PageTwo(title, "", key, 0);
    }

    @Override
    public Page getPage() {
        return new Page("http://www.zjgsu.edu.cn/Channel_7/Page_","校园风光");
    }

    @Override
    public Elements getMain(Document document) {
        return document.select("[width=20%]").select("tr");
    }

    @Override
    public void addPhoto(Elements elements) {

    }

    @Autowired
    SmartWebDAO dao;

    @Override
    @Transactional
    public void resolver() {
        Page page = getPage();
        String category = page.getCategory();
        String url = page.getUrl();
        for (int i = 1; true; i++) {
            List<PageTwo> pageTwos = new ArrayList<PageTwo>();
            Document document = null;
            try {
                document = WebsiteUtil.getDocByURL(url + i + ".html");
                if (document == null)
                    break;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Elements elements = getMain(document);
            dealPhotoAndFile(elements);
            getPageTwo(category, elements, pageTwos);
            dao.insertListPageTwo(pageTwos);
        }
    }

}
